<template>
	<div>
		<el-upload 
			ref="elUpload"
			class="upload-box" 
			:action="baseUrl+'/api/tools/btachUpload'" 
			:accept="accept"
			:show-file-list="false" 
			:on-success="handleUploadSuccess" 
			:http-request="upload"
			:before-upload="beforeUpload">
	
			<div class="uploading flex flex-align-center flex-justify-center" v-if="uploading">正在上传...</div>
			<slot v-if="!imageUrl&&!uploading"></slot>
			<slot slot="tip" name="tip">
				<p></p>
			</slot>
	
		</el-upload>
		<div class="upload-cover" v-if="imageUrl&&!uploading">
			<slot></slot>
			<img :src="imageUrl"  @click="viewImage(imageUrl)" class="img">
		</div>
		<view-img :src="imgSrc" v-if="showImg" @close="closeImg"></view-img>
	</div>
	

</template>

<script>
	import { apiBaseUrl } from '@/utils/common'
	export default {
		name: 'ImageUploader',
		props: {
			imageUrl:{
				type: String,
				default:'',
			},
			accept: {
				type: String,
				default: 'image/*'
			},
			fileSizeLimit: {
				type: Number,
				default: 0
			}
		},

		data() {
			return {
				baseUrl: apiBaseUrl,
				uploading: false,
			}
		},
		mounted() {
		},
		methods: {
			handleUploadSuccess: function(res) {
				if(!res){
					return
				}
				this.uploading = false
				console.log(res)
				if(res.code == 0) {
					var obj=res.objlist[0] ? res.objlist[0] :null
					if(obj==null){
						this.$message.error('上传失败')
					}
					else{
						if(obj.code==0){
							this.$emit('success', obj)
						}
						else{
							this.$message.error(obj.msg)
						}
					}
					
				} else {
					this.$message.error(res.msg)
				}
			},
			beforeUpload(file) {
				if(this.fileSizeLimit && file.size > this.fileSizeLimit * 1024) {
					this.$message({
						type: 'error',
						message: '上传文件过大',
					})
					return false
				}
			},
			async upload(param){
				this.uploading = true
				var formData=new FormData()
				formData.append('file',param.file)
				var res=await this.$request.uploadFile(formData)
				param.onSuccess(res)
			},
			selectFile(){
				this.$refs.elUpload.$el.querySelector('[type=file]').click()
			},
			clearFile(){
				this.$refs.elUpload.clearFiles()
			},
		}
	}
</script>

<style lang="scss" scoped>
>>>.upload-box{
	width: 100%;
	height: 100%;
	.el-upload{
		width: 100%;
		height: 100%;
		position: relative;
		background: #fff;
		.uploading {
			height: 100%;
			color: #3A8EE6;
		}
	}
}
.upload-cover{
	position: absolute;
	width: 100%;
	height: 100%;
	left: 0;
	top: 0;
	border: 1px solid #eee;
	.img {
		width: 100%;
		height: 100%;
		display: block;
	}
}
</style>